﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;

namespace WindowsServicesByGetRoleInfo
{
    partial class GetPersonTrainLenrnInfo : ServiceBase
    {
        public GetPersonTrainLenrnInfo()
        {
            InitializeComponent();
        }

        //全局变量记录日志
        log4net.ILog Log = log4net.LogManager.GetLogger(typeof(GetPersonTrainLenrnInfo));


        /// <summary>
        ///  // TODO: 在此处添加代码以启动服务。
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            Log.Info("服务开始启动！");



            try
            {
                //开启线程来补增日期数据
                //Thread thread = new Thread(new ThreadStart(SupplementDateData));
                //thread.Start();
                Task t = Task.Run(() => SupplementDateData());


                System.Timers.Timer time = new System.Timers.Timer();
                time.Interval = 1000;
                time.Elapsed += new System.Timers.ElapsedEventHandler(ChkSrv);//到达时间的时候执行事件；    
                time.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；    
                time.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；    

            }
            catch (Exception ex)
            {
                Log.Info("服务启动过程中出现异常，异常信息:" + ex.Message.ToString());
                throw;
            }
        }

        private void ChkSrv(object sender, ElapsedEventArgs e)
        {

            try
            {
                int intHour = e.SignalTime.Hour;
                int intMinute = e.SignalTime.Minute;
                int intSecond = e.SignalTime.Second;
                List<int> execTime = System.Configuration.ConfigurationManager.AppSettings["EverydayDate"].ToString().Split(new char[] { ':' }).Select(x => Convert.ToInt32(x)).ToList();
                if (intHour == execTime[0] && intMinute == execTime[1] && intSecond == execTime[2])
                {
                    Log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "开始请求接口。");
                    string resString = WebApiUtil.HttpPost("http://10.99.101.28:90/SysBaseInfo.asmx/GetRolesInfo", "wyappuser", "1qaz2wsx");
                    Result res = new Result();
                    res = JsonConvert.DeserializeObject<Result>(resString);
                    foreach (RoleInfo item in res.Data)
                    {
                        SqlUtil.Save(item);
                    }
                    Log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "请求接口完毕。");
                    Log.Info("服务启动完毕，数据已导入数据库");
                }
            }
            catch (Exception ex)
            {
                Log.Info("执行每日定时任务时发生异常,异常名称:" + ex.GetType().Name + "，异常内容" + ex.Message.ToString(), ex);
            }
        }

        /// <summary>
        /// 补充指定的日期数据
        /// </summary>
        protected void SupplementDateData()
        {
            string SupplementDate = System.Configuration.ConfigurationManager.AppSettings["Dates"].ToString();
            List<string> dates = SupplementDate.Split(',').ToList();
            Log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "开始请求补充日期数据。");
            foreach (string date in dates)
            {
                Log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "开始请求接口。统计日期:" + date);
                string resString = WebApiUtil.HttpPost("http://10.99.101.28:90/SysBaseInfo.asmx/GetRolesInfo", "wyappuser", "1qaz2wsx");
                Result res = new Result();
                res = JsonConvert.DeserializeObject<Result>(resString);
                foreach (RoleInfo item in res.Data)
                {
                    SqlUtil.Save(item);
                }
                Log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "请求接口完毕。统计日期:" + date);
            }
            Log.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "请求补充日期数据完成。");
        }


        /// <summary>
        ///  // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        /// </summary>
        protected override void OnStop()
        {
            Log.Info("服务停止！");
        }

        /// <summary>
        /// 服务暂停
        /// </summary>
        protected override void OnPause()
        {
            Log.Info("服务暂停！");
        }

        /// <summary>
        /// 服务继续时
        /// </summary>
        protected override void OnContinue()
        {
            Log.Info("服务暂停后继续！");
        }

        /// <summary>
        /// 系统关闭时
        /// </summary>
        protected override void OnShutdown()
        {
            Log.Info("系统关闭，服务已停止！");
        }


    }
}
